﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using SHOP.Areas.Admin.Models;

namespace SHOP.Areas.Admin.Controllers
{
    public class OrdersController : Controller
    {
        //
        // GET: /Admin/Orders/
        ProductModelDataContext dataTable = new ProductModelDataContext();

        public Constants Constants = new Constants();
        public string NameController = "orders";

        public ActionResult Index()
        {
            //Delete Multi Record
            string[] items = Request.Form.GetValues("items");

            if (items != null)
            {
                foreach (var value in items)
                {
                    var ItemAccount = dataTable.orders.Single(b => b.id == int.Parse(value));
                    dataTable.orders.DeleteOnSubmit(ItemAccount);
                    dataTable.SubmitChanges();
                }

                return Redirect("/admin/" + NameController + "#success");
            }

            return View();
        }

        public ActionResult purchased()
        {
            //Delete Multi Record
            string[] items = Request.Form.GetValues("items");

            if (items != null)
            {
                foreach (var value in items)
                {
                    var ItemAccount = dataTable.orders.Single(b => b.id == int.Parse(value));
                    dataTable.orders.DeleteOnSubmit(ItemAccount);
                    dataTable.SubmitChanges();
                }

                return Redirect("/admin/" + NameController + "/purchased#success");
            }

            return View();
        }

        [HandleError,HttpPost]
        public ActionResult LoadContent()
        {
            string Sort_By = "";
            string Sort_Type = "";
            string Search_Type = "fullname";
            string KeyWord = Request.Form["keyword"];

            string[] Columns = { "name", "phone", "status", "created", "changed" };
            string sortby = Array.Find(Columns, delegate(string s) { return s == Request.Form["sort_by"]; });

            string[] Sort = { "asc", "desc" };
            string sorttype = Array.Find(Sort, delegate(string s) { return s == Request.Form["sort_type"]; });

            if (sortby != null) { Sort_By = sortby; } else { Sort_By = "id"; };
            if (sorttype != null) { Sort_Type = sorttype; } else { Sort_Type = "desc"; };

            //Pagination
            var page = int.Parse(Request.Form["page"]);
            if (KeyWord != "")
            {
                var ListItem = (from u in dataTable.orders where u.status == 0 select u).Where(Search_Type + ".Contains(@0)", KeyWord).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dataTable.orders where u.status == 1 select u).Where(Search_Type + ".Contains(@0)", KeyWord).Count();
                ViewBag.View = ListItem;

            }
            else
            {
                var ListItem = (from u in dataTable.orders select u).Where("status == @0", 0).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dataTable.orders select u).Where("status == @0", 0).Count();
                ViewBag.View = ListItem;
            }

            ViewBag.Page = page;
            ViewBag.Keyword = KeyWord;
            ViewBag.Sort_By = Sort_By;
            ViewBag.Sort_Type = Sort_Type;
            ViewBag.pageSize = Constants.pageSize;

            return View();
        }

        [HandleError, HttpPost]
        public ActionResult LoadContentPurchased()
        {
            string Sort_By = "";
            string Sort_Type = "";
            string Search_Type = "fullname";
            string KeyWord = Request.Form["keyword"];

            string[] Columns = { "name", "phone", "status", "created", "changed" };
            string sortby = Array.Find(Columns, delegate(string s) { return s == Request.Form["sort_by"]; });

            string[] Sort = { "asc", "desc" };
            string sorttype = Array.Find(Sort, delegate(string s) { return s == Request.Form["sort_type"]; });

            if (sortby != null) { Sort_By = sortby; } else { Sort_By = "id"; };
            if (sorttype != null) { Sort_Type = sorttype; } else { Sort_Type = "desc"; };

            //Pagination
            var page = int.Parse(Request.Form["page"]);
            if (KeyWord != "")
            {
                var ListItem = (from u in dataTable.orders where u.status == 1 select u).Where(Search_Type + ".Contains(@0)", KeyWord).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dataTable.orders where u.status == 1 select u).Where(Search_Type + ".Contains(@0)", KeyWord).Count();
                ViewBag.View = ListItem;

            }
            else
            {
                var ListItem = (from u in dataTable.orders select u).Where("status == @0", 1).OrderBy(Sort_By + " " + Sort_Type).Skip((page - 1) * Constants.pageSize).Take(Constants.pageSize).ToList();
                ViewBag.numPage = (from u in dataTable.orders select u).Where("status == @0", 1).Count();
                ViewBag.View = ListItem;
            }

            ViewBag.Page = page;
            ViewBag.Keyword = KeyWord;
            ViewBag.Sort_By = Sort_By;
            ViewBag.Sort_Type = Sort_Type;
            ViewBag.pageSize = Constants.pageSize;

            return View();
        }

        public class ProductDetail
        {
            public int id { get; set; }
            public string code { get; set; }
            public string name { get; set; }
            public string image { get; set; }
            public int price { get; set; }
            public int sale { get; set; }
            public int qty { get; set; }
        }

        [HandleError, HttpPost]
        public ActionResult detail()
        {
            if (Request.Form["oid"] != null || System.Text.RegularExpressions.Regex.IsMatch(Request.Form["oid"], @"\d"))
            {
                ViewBag.Product = (from o in dataTable.purchaseds
                                   join p in dataTable.products on o.pid equals p.id
                                   where o.oid == int.Parse(Request.Form["oid"])
                                   select new ProductDetail
                                   {
                                       id = o.id,
                                       code = p.code,
                                       name = p.name,
                                       image = p.image,
                                       price = p.price.Value,
                                       sale = (p.sale == null) ? 0 : p.sale.Value,
                                       qty = o.quantity.Value
                                   }).ToList();
            }
            return View();
        }

        [HandleError, HttpPost]
        public ActionResult Status()
        {
            //Update
            var json = "";

            int id = Convert.ToInt32(Request.Form["id"]);
            int recCount = dataTable.orders.Count(b => b.id == id);

            if (recCount > 0)
            {
                var ListItem = dataTable.orders.Single(b => b.id == id);
                ListItem.status = int.Parse(Request.Form["status"]);
                dataTable.SubmitChanges();
                json = "success";
            }
            else
            {
                json = "fail";
            }

            return Json(new { st = json });
        }

    }
}
